package com.github.baichuan.web.gateway;

import com.github.baichuan.web.security.JwtCodec;
import com.github.baichuan.web.security.PrincipalPayload;
import com.github.baichuan.web.utils.BearerToken;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Optional;

public class HeaderAppendAuthorizationFilter implements GatewayFilter {
    private JwtCodec<? extends PrincipalPayload> jwtCodec;

    public HeaderAppendAuthorizationFilter(JwtCodec<? extends PrincipalPayload> jwtCodec) {
        this.jwtCodec = jwtCodec;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        Optional<String> optional = BearerToken.get(request);
        if(optional.isPresent()){
            PrincipalPayload payload = jwtCodec.decode(optional.get());
            String codes = String.join(",", payload.getAuthorizations());
            request.mutate().header("x-authorization-code", codes).build();
        }

        return chain.filter(exchange);
    }
}
